package com.zhiyou100.springbootweather.service.imp;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhiyou100.springbootweather.pojo.Forecast;
import com.zhiyou100.springbootweather.pojo.WeatherResponse;
import com.zhiyou100.springbootweather.service.IWeatherDataService;
import com.zhiyou100.springbootweather.util.RedisUtils;
import io.netty.handler.timeout.ReadTimeoutException;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.Key;
import java.util.Set;

@Service("weatherDataService")
public class WeatherDataServiceImpl implements IWeatherDataService {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisUtils redisUtils;
    //定义获取连接地址,后边只需要加上 名字或id即可
    private static final String url = "http://wthrcdn.etouch.cn/weather_mini?";

    /*根据城市id查询*/
    @Override
    public WeatherResponse getDataByCityId(String cityId) {

        return getData(url + "citykey=" + cityId);

    }

    /*根据城市名查询*/
    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        return getData(url+"city="+cityName);
    }

    /**
     * 查询
     * @param uri
     * @return
     */
    private WeatherResponse getData(String uri) {
        //建立一个返回对象
        WeatherResponse weatherResponse =null;
        //解析JSON对象
        ObjectMapper objectMapper = new ObjectMapper();

        //判断redis中是否有数据
        if(redisUtils.hasKey(uri)){
            //获取数据
            String body = (String) redisUtils.get(uri);
            try {
                //将json转成对象返回
                 weatherResponse = objectMapper.readValue(body, WeatherResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return  weatherResponse;
        }
        //从接口中拿取数据
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
        //JSON数据
        String body = null;
        //判断如果状态==200
        if (responseEntity.getStatusCodeValue() == 200) {
            body = responseEntity.getBody();

            //向redis中存储一份数据
            redisUtils.set(uri,body);
        }
        try {
            weatherResponse = objectMapper.readValue(body, WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return weatherResponse;
    }
}
